import axios from 'axios'
// import { userInfo } from '@/config'
import useAxiosConfig from '@/hooks/useAxiosConfig'
import type { RequestConfig } from '@/types/services/http'
const config = {
  method: `post`,
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 1000 * 60 * 30,
}

// if (import.meta.env.MODE === `development`) {
//   axios.defaults.headers.post[`X-Remote-User`] = userInfo.userName
//   axios.defaults.headers.post[`X-Remote-Uid`] = userInfo.userId
// }

const _axios = axios.create(config)

const { setRequest, setLoading, deleteLoading, cancelDuplicateRequest, errorHandler } =
  useAxiosConfig(_axios)

// 请求拦截器
_axios.interceptors.request.use(
  config => {
    //添加loading
    setLoading(config)
    //取消重复请求
    cancelDuplicateRequest(config)

    return config
  },
  error => {
    return errorHandler(error)
  }
)

// 响应拦截器
_axios.interceptors.response.use(
  async res => {
    //关闭局部加载loading
    deleteLoading(res.config)

    //后台状态码处理
    if (
      String(res.data.code) === `000000` ||
      (res.data.head && String(res.data.head.code) === `1001`)
    ) {
      return Promise.resolve(res.data.data)
    } else {
      return errorHandler(res.data)
    }
  },
  error => {
    const config = error.config || error.message.config
    //关闭loading
    deleteLoading(config)

    if (config.isCancelToken) {
      return Promise.reject(error)
    } else {
      return errorHandler(error)
    }
  }
)

const get = async (url = ``, params: any = {}, config?: RequestConfig): Promise<any> => {
  return setRequest(_axios.request, { url, params, method: `get`, ...config })
}

const post = async (url = ``, params: any = {}, config?: RequestConfig): Promise<any> => {
  return setRequest(_axios.request, { url, params, method: `post`, ...config })
}

export { get, post }
